//
//  NSDictionary+Safe.m
//  CommonTool
//
//  Created by Name i on 2022/4/14.
//

#import "NSDictionary+Safe.h"

@implementation NSDictionary (Safe)

+ (void)exchangeMethod {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [NSObject tnSwizzlingClassMethod:@selector(dictionaryWithObjects:forKeys:count:)
                              withMethod:@selector(safe_dictionaryWithObjects:forKeys:count:)
                               withClass:[self class]];
    });
}


+ (instancetype)safe_dictionaryWithObjects:(id  _Nonnull const [])objects forKeys:(id<NSCopying>  _Nonnull const [])keys count:(NSUInteger)cnt {
    
    id instance = nil;
    
    @try {
        instance = [self safe_dictionaryWithObjects:objects forKeys:keys count:cnt];
    }
    @catch (NSException *exception) {
        [NNDefender crashWithException:exception defaultToDo:@"NNDefender default is to remove nil key-values and instance a dictionary."];

        //处理错误的数据，然后重新初始化一个字典
        NSUInteger index = 0;
        id  _Nonnull __unsafe_unretained newObjects[cnt];
        id  _Nonnull __unsafe_unretained newkeys[cnt];
        
        for (int i = 0; i < cnt; i++) {
            if (objects[i] && keys[i]) {
                newObjects[index] = objects[i];
                newkeys[index] = keys[i];
                index++;
            }
        }
        instance = [self safe_dictionaryWithObjects:objects forKeys:keys count:cnt];
    }
    @finally {
        return instance;
    }
}
@end
